package com.eu.ebpm.engine.script;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.stereotype.Service;

import com.eu.ebpm.Constants;
import com.eu.ebpm.engine.entity.deploy.Mission;
import com.eu.ebpm.engine.entity.runtime.TaskEntity;
import com.eu.ebpm.engine.repository.ExecutionRepository;

@Service
public class SpelScriptService {

	@Autowired
	private SpringEvaluationContext springEvaluationContext;
	
	@Autowired
	private ExecutionRepository executionRepository;

	private ExpressionParser parser = new SpelExpressionParser();
	
	public void initAssignee(Mission m, TaskEntity task) {
		// 1、判断是否是spel表达式
		if (m.getAssignee().contains("#")) {
			String express = m.getAssignee();
			if (express.contains(Constants.DEF_ASSIGNEE)) {
				express = express.replace(Constants.DEF_ASSIGNEE, "'" + task.getAssignee() + "'");
			} else if(m.getAssignee().equals(Constants.DEF_EXE_USER)) {
				String assignee = executionRepository.queryById(task.getRootExecutionId()).getUser();
				task.setAssignee(assignee);
				return ;
			} else if (m.getAssignee().contains(Constants.DEF_EXE_USER)) {
				String assignee = executionRepository.queryById(task.getRootExecutionId()).getUser();
				express = express.replace(Constants.DEF_EXE_USER, "'" + assignee + "'");
			}
			String assignee = (String) parser.parseExpression(express).getValue(springEvaluationContext);
			task.setAssignee(assignee);
		} else {
			task.setAssignee(m.getAssignee());
		}
	}
	
}
